#import "PhotoRecordViewController.h"

@implementation PhotoRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.97 alpha:1.0];
    self.title = @"拍照记录";
    
    // 添加导航栏按钮 - 使用 back 图片
    UIImage *backImage = [UIImage imageNamed:@"back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    // 添加点击手势来隐藏键盘
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    tapGesture.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGesture];
    
    [self setupUI];
    [self setupConstraints];
}

- (void)setupUI {
    // 滚动视图
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    // 内容视图
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];
    
    // 照片预览区域
    UIView *photoSection = [self createSectionWithTitle:@"物品照片"];
    [self.contentView addSubview:photoSection];
    
    self.photoImageView = [[UIImageView alloc] init];
    self.photoImageView.translatesAutoresizingMaskIntoConstraints = NO;
    self.photoImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.photoImageView.clipsToBounds = YES;
    self.photoImageView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    self.photoImageView.layer.cornerRadius = 12;
    self.photoImageView.layer.borderWidth = 2;
    self.photoImageView.layer.borderColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1.0].CGColor;
    [photoSection addSubview:self.photoImageView];
    
    // 拍照按钮
    self.cameraButton = [[UIButton alloc] init];
    self.cameraButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cameraButton setTitle:@"📷 拍照" forState:UIControlStateNormal];
    [self.cameraButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.cameraButton.backgroundColor = [UIColor colorWithRed:0.2 green:0.6 blue:1.0 alpha:1.0];
    self.cameraButton.layer.cornerRadius = 25;
    self.cameraButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [self.cameraButton addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    [photoSection addSubview:self.cameraButton];
    
    // 相册按钮
    self.albumButton = [[UIButton alloc] init];
    self.albumButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.albumButton setTitle:@"🖼️ 相册" forState:UIControlStateNormal];
    [self.albumButton setTitleColor:[UIColor colorWithRed:0.2 green:0.6 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
    self.albumButton.backgroundColor = [UIColor whiteColor];
    self.albumButton.layer.cornerRadius = 25;
    self.albumButton.layer.borderWidth = 2;
    self.albumButton.layer.borderColor = [UIColor colorWithRed:0.2 green:0.6 blue:1.0 alpha:1.0].CGColor;
    self.albumButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [self.albumButton addTarget:self action:@selector(selectFromAlbum) forControlEvents:UIControlEventTouchUpInside];
    [photoSection addSubview:self.albumButton];
    
    // 物品信息区域
    UIView *infoSection = [self createSectionWithTitle:@"物品信息"];
    [self.contentView addSubview:infoSection];
    
    // 物品名称
    self.nameField = [[UITextField alloc] init];
    self.nameField.translatesAutoresizingMaskIntoConstraints = NO;
    self.nameField.placeholder = @"请输入物品名称";
    self.nameField.borderStyle = UITextBorderStyleRoundedRect;
    self.nameField.backgroundColor = [UIColor whiteColor];
    self.nameField.layer.cornerRadius = 8;
    self.nameField.font = [UIFont systemFontOfSize:16];
    self.nameField.delegate = self;
    self.nameField.returnKeyType = UIReturnKeyNext;
    [infoSection addSubview:self.nameField];
    
    // 物品描述
    self.descTextView = [[UITextView alloc] init];
    self.descTextView.translatesAutoresizingMaskIntoConstraints = NO;
    self.descTextView.backgroundColor = [UIColor whiteColor];
    self.descTextView.layer.cornerRadius = 8;
    self.descTextView.layer.borderWidth = 1;
    self.descTextView.layer.borderColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1.0].CGColor;
    self.descTextView.font = [UIFont systemFontOfSize:16];
    self.descTextView.delegate = self;
    [infoSection addSubview:self.descTextView];
    
    // 占位符标签
    self.placeholderLabel = [[UILabel alloc] init];
    self.placeholderLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.placeholderLabel.text = @"请输入物品描述或存放位置";
    self.placeholderLabel.textColor = [UIColor lightGrayColor];
    self.placeholderLabel.font = [UIFont systemFontOfSize:16];
    [self.descTextView addSubview:self.placeholderLabel];
    
    // 分类选择
    UILabel *categoryLabel = [[UILabel alloc] init];
    categoryLabel.translatesAutoresizingMaskIntoConstraints = NO;
    categoryLabel.text = @" ";
    categoryLabel.font = [UIFont boldSystemFontOfSize:16];
    categoryLabel.textColor = [UIColor darkGrayColor];
    [infoSection addSubview:categoryLabel];
    
    self.categorySegment = [[UISegmentedControl alloc] initWithItems:@[@"日用品", @"电子产品", @"文件证件", @"其他"]];
    self.categorySegment.translatesAutoresizingMaskIntoConstraints = NO;
    self.categorySegment.selectedSegmentIndex = 0;
    self.categorySegment.backgroundColor = [UIColor whiteColor];
    self.categorySegment.selectedSegmentTintColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
    [infoSection addSubview:self.categorySegment];
    
    // 保存按钮
    self.saveButton = [[UIButton alloc] init];
    self.saveButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.saveButton setTitle:@"保存记录" forState:UIControlStateNormal];
    [self.saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.saveButton.backgroundColor = [UIColor colorWithRed:1.0 green:0.54 blue:0.40 alpha:1.0];
    self.saveButton.layer.cornerRadius = 25;
    self.saveButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.saveButton addTarget:self action:@selector(saveRecord) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.saveButton];
    
    // 设置约束
    [self setupPhotoSectionConstraints:photoSection];
    [self setupInfoSectionConstraints:infoSection];
}

- (UIView *)createSectionWithTitle:(NSString *)title {
    UIView *section = [[UIView alloc] init];
    section.translatesAutoresizingMaskIntoConstraints = NO;
    section.backgroundColor = [UIColor whiteColor];
    section.layer.cornerRadius = 12;
    section.layer.shadowColor = [UIColor blackColor].CGColor;
    section.layer.shadowOffset = CGSizeMake(0, 2);
    section.layer.shadowOpacity = 0.1;
    section.layer.shadowRadius = 4;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.text = title;
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textColor = [UIColor darkGrayColor];
    [section addSubview:titleLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [titleLabel.topAnchor constraintEqualToAnchor:section.topAnchor constant:16],
        [titleLabel.leadingAnchor constraintEqualToAnchor:section.leadingAnchor constant:16],
        [titleLabel.trailingAnchor constraintEqualToAnchor:section.trailingAnchor constant:-16]
    ]];
    
    return section;
}

- (void)setupConstraints {
    [NSLayoutConstraint activateConstraints:@[
        // 滚动视图
        [self.scrollView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        // 内容视图
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
        
        // 保存按钮
        [self.saveButton.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
        [self.saveButton.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20],
        [self.saveButton.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-30],
        [self.saveButton.heightAnchor constraintEqualToConstant:50]
    ]];
}

- (void)setupPhotoSectionConstraints:(UIView *)photoSection {
    [NSLayoutConstraint activateConstraints:@[
        [photoSection.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:20],
        [photoSection.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
        [photoSection.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20],
        [photoSection.heightAnchor constraintEqualToConstant:320],
        
        // 照片预览
        [self.photoImageView.topAnchor constraintEqualToAnchor:photoSection.topAnchor constant:60],
        [self.photoImageView.leadingAnchor constraintEqualToAnchor:photoSection.leadingAnchor constant:20],
        [self.photoImageView.trailingAnchor constraintEqualToAnchor:photoSection.trailingAnchor constant:-20],
        [self.photoImageView.heightAnchor constraintEqualToConstant:180],
        
        // 拍照按钮
        [self.cameraButton.topAnchor constraintEqualToAnchor:self.photoImageView.bottomAnchor constant:20],
        [self.cameraButton.leadingAnchor constraintEqualToAnchor:photoSection.leadingAnchor constant:20],
        [self.cameraButton.widthAnchor constraintEqualToConstant:140],
        [self.cameraButton.heightAnchor constraintEqualToConstant:50],
        
        // 相册按钮
        [self.albumButton.topAnchor constraintEqualToAnchor:self.photoImageView.bottomAnchor constant:20],
        [self.albumButton.trailingAnchor constraintEqualToAnchor:photoSection.trailingAnchor constant:-20],
        [self.albumButton.widthAnchor constraintEqualToConstant:140],
        [self.albumButton.heightAnchor constraintEqualToConstant:50]
    ]];
}

- (void)setupInfoSectionConstraints:(UIView *)infoSection {
    UIView *photoSection = [self.contentView.subviews firstObject];
    
    [NSLayoutConstraint activateConstraints:@[
        [infoSection.topAnchor constraintEqualToAnchor:photoSection.bottomAnchor constant:20],
        [infoSection.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
        [infoSection.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20],
        [infoSection.bottomAnchor constraintEqualToAnchor:self.saveButton.topAnchor constant:-20],
        
        // 物品名称
        [self.nameField.topAnchor constraintEqualToAnchor:infoSection.topAnchor constant:60],
        [self.nameField.leadingAnchor constraintEqualToAnchor:infoSection.leadingAnchor constant:16],
        [self.nameField.trailingAnchor constraintEqualToAnchor:infoSection.trailingAnchor constant:-16],
        [self.nameField.heightAnchor constraintEqualToConstant:44],
        
        // 物品描述
        [self.descTextView.topAnchor constraintEqualToAnchor:self.nameField.bottomAnchor constant:16],
        [self.descTextView.leadingAnchor constraintEqualToAnchor:infoSection.leadingAnchor constant:16],
        [self.descTextView.trailingAnchor constraintEqualToAnchor:infoSection.trailingAnchor constant:-16],
        [self.descTextView.heightAnchor constraintEqualToConstant:80],
        
        // 占位符
        [self.placeholderLabel.topAnchor constraintEqualToAnchor:self.descTextView.topAnchor constant:8],
        [self.placeholderLabel.leadingAnchor constraintEqualToAnchor:self.descTextView.leadingAnchor constant:8],
        
        // 分类标签和选择器
        [infoSection.subviews[2].topAnchor constraintEqualToAnchor:self.descTextView.bottomAnchor constant:20],
        [infoSection.subviews[2].leadingAnchor constraintEqualToAnchor:infoSection.leadingAnchor constant:16],
        
        [self.categorySegment.topAnchor constraintEqualToAnchor:infoSection.subviews[2].bottomAnchor constant:8],
        [self.categorySegment.leadingAnchor constraintEqualToAnchor:infoSection.leadingAnchor constant:16],
        [self.categorySegment.trailingAnchor constraintEqualToAnchor:infoSection.trailingAnchor constant:-16],
        [self.categorySegment.bottomAnchor constraintEqualToAnchor:infoSection.bottomAnchor constant:-16]
    ]];
}

#pragma mark - Actions

- (void)takePhoto {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备不支持拍照功能" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)selectFromAlbum {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)saveRecord {
    if (!self.imagePath || self.nameField.text.length == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请拍摄照片并填写物品名称" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    NSArray *categories = @[@"日用品", @"电子产品", @"文件证件", @"其他"];
    NSString *category = categories[self.categorySegment.selectedSegmentIndex];
    
    NSDictionary *itemData = @{
        @"name": self.nameField.text,
        @"desc": self.descTextView.text ?: @"",
        @"category": category,
        @"time": [self getCurrentTimeString],
        @"imagePath": self.imagePath
    };
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didFinishPhotoRecordWithData:)]) {
        [self.delegate didFinishPhotoRecordWithData:itemData];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)cancelAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)getCurrentTimeString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM-dd HH:mm";
    return [formatter stringFromDate:[NSDate date]];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage];
    
    // 保存图片到本地
    NSString *imageName = [NSString stringWithFormat:@"item_%@.jpg", @([[NSDate date] timeIntervalSince1970])];
    self.imagePath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName];
    [UIImageJPEGRepresentation(image, 0.8) writeToFile:self.imagePath atomically:YES];
    
    // 显示预览
    self.photoImageView.image = image;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    self.placeholderLabel.hidden = textView.text.length > 0;
}

#pragma mark - Keyboard Management

- (void)dismissKeyboard {
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 移除键盘通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardFrame.size.height;
    NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
        self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset;
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSTimeInterval animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.scrollView.contentInset = UIEdgeInsetsZero;
        self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.nameField) {
        [self.descTextView becomeFirstResponder];
    }
    return YES;
}

@end
